<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="goodsCode">
        <el-input
          v-model="queryParams.goodsCode"
          placeholder="请输入商品编码"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="产品条码" prop="barCode">
        <el-input
          v-model="queryParams.barCode"
          placeholder="请输入产品条码"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="分类状态" clearable>
            <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['product:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['product:goods:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      row-key="key"
      v-loading="loading"
      :data="goodsList"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
      :lazy="true"
      :load="loadTreeData"
    >
      <el-table-column 
      type="selection" 
      :selectable="handleSelectable"
      width="30" align="center" ></el-table-column>
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column
        label="名称"
        align="center"
        width="200"
        prop="goodsName"
      />
      <el-table-column label="图片" align="center" prop="mainImg">
        <template #default="scope">
          <el-image
            width="98"
            height="98"
            v-if="scope.row.mainImg"
            :src="scope.row.mainImg"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        width="180"
        label="商品编码/规格编码"
        align="center"
        prop="goodsCode"
      >
      <template #default="scope">
        <span v-if="scope.row.hasChildren">{{scope.row.goodsCode}}</span>
        <span v-if="!scope.row.hasChildren" style="padding-left:30px;">{{scope.row.specCode}}</span>
        
      </template>
      </el-table-column>
      <!-- <el-table-column
        width="160"
        label="规格编码"
        align="center"
        prop="specCode"
      /> -->
      <el-table-column label="价格" align="center" prop="salePrice" />
      <el-table-column label="销量" align="center" prop="saleNum" />
      <el-table-column label="状态" align="center" prop="status" >
        <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="品牌名称" align="center" prop="brandName" /> -->
      <!-- <el-table-column label="店铺名称" align="center" prop="storeName" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        sortable="custom"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.hasChildren"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:goods:edit']"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.hasChildren"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1080px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-card>
          <template #header>
            <div>
              <span>商品信息</span>
            </div>
          </template>
          <div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input
                    v-model="form.goodsName"
                    placeholder="请输入商品名称"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <!-- <el-col :span="12">
                <el-form-item label="商品编码" prop="goodsCode">
                  <el-input
                    v-model="form.goodsCode"
                    placeholder="请输入商品编码"
                  />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="产品条码" prop="barCode">
                  <el-input
                    v-model="form.barCode"
                    placeholder="请输入产品条码"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="商品简介" prop="goodsTitle">
                  <el-input
                    v-model="form.goodsTitle"
                    placeholder="请输入商品简介"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="关键字" prop="keyword">
                  <el-input v-model="form.keyword" placeholder="请输入关键字" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="品牌">
                  <el-select v-model="form.brandId" placeholder="请选择品牌">
                    <el-option
                      v-for="item in brandOptions"
                      :key="item.id"
                      :label="item.brandName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="分类">
                  <el-cascader
                    clearable
                    v-model="form.categoryList"
                    :options="categoryOptions"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="商品主图">
                  <span v-if="form.mainImg">
                          <el-image
                            style="width: 40px; height: 40px"
                            v-for="img in form.mainImg.split(',')"
                            :key="img"
                            size="small"
                            :src="img"
                          ></el-image>
                        </span>
                  <el-button
                          type="text"
                          size="small"
                          icon="upload-filled"
                          @click="
                            () => {
                              let callback = () => {
                                form.mainImg = getSubImg();
                              };
                              handleImgUploadClick(form.mainImg,1,callback);
                            }
                          "
                          >上传</el-button
                        >

                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="商品详情">
                  <!-- <ImageUpload
                    :modelValue="form.goodsDetail"
                    :limit="9"
                    @update:modelValue="(val) => (form.value.goodsDetail = val)"
                  ></ImageUpload> -->
                  <span v-if="form.goodsDetail">
                          <el-image
                            style="width: 100px; height: 100px"
                            v-for="img in form.goodsDetail.split(',')"
                            :key="img"
                            size="small"
                            :src="img"
                          ></el-image>
                        </span>
                  <el-button
                          type="text"
                          size="small"
                          icon="upload-filled"
                          @click="
                            () => {
                              let callback = () => {
                                form.goodsDetail = getSubImg();
                              };
                              handleImgUploadClick(form.goodsDetail,9,callback);
                            }
                          "
                          >上传</el-button
                        >
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-form-item label="运费模板 " prop="freightTemplateId">
          <el-input v-model="form.freightTemplateId" placeholder="请输入运费模板 " />
        </el-form-item> -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="商品单位" prop="unitName">
                  <el-input
                    v-model="form.unitName"
                    placeholder="请输入商品单位"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="虚拟销量" prop="fictiNum">
                  <el-input
                    v-model="form.fictiNum"
                    placeholder="请输入虚拟销量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="规格类型">
                  <el-select
                    v-model="form.specType"
                    placeholder="请选择规格类型"
                    @change="handleSpecTypeChange"
                  >
                    <el-option
                      v-for="item in specTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.specType > 0">
                <el-form-item label="规格一" prop="firstSpecName">
                  <el-input
                    v-model="form.firstSpecName"
                    placeholder="请输入规格一名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.specType > 1">
                <el-form-item label="规格二" prop="secondSpecName">
                  <el-input
                    v-model="form.secondSpecName"
                    placeholder="请输入规格二名称"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-form>

        <el-card class="mt-20">
          <template #header>
            <div>
              <span>规格信息</span>
            </div>
          </template>
          <div>
          <!-- 默认规格 -->
          <div>
            <el-form ref="formRef2" :model="defaultSpec" :rules="rules" label-width="80px">
            <el-row :span="24" v-if="form.specType === 0">
              <el-col :span="8">
                
                <!-- <el-form-item label="规格编码">
                  <el-input
                    type="text"
                    v-model="defaultSpec.specCode"
                    placeholder="规格编码"
                  ></el-input>
                </el-form-item> -->
                <el-form-item label="市场价" prop="marketPrice">
                  <el-input
                    type="number"
                    v-model="defaultSpec.marketPrice"
                    placeholder="市场价"
                  ></el-input>
                </el-form-item>
                <el-form-item label="成本价" prop="costPrice">
                  <el-input
                    type="number"
                    v-model="defaultSpec.costPrice"
                    placeholder="成本价"
                  ></el-input>
                </el-form-item>
                <el-form-item label="售价" prop="salePrice">
                  <el-input
                    type="number"
                    v-model="defaultSpec.salePrice"
                    placeholder="售价"
                  ></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="stockNum">
                  <el-input
                    type="number"
                    v-model="defaultSpec.stockNum"
                    placeholder="库存"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            </el-form>
          </div>
          
            <!-- 规格一 -->
            <div v-if="form.specType > 0">
              <el-row>
                <el-col :span="2">
                  <span>{{form.firstSpecName}}</span>
                </el-col>
                <el-col :span="4">
                  <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="ml-1 w-20 mb8"
                    size="small"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                  />
                  <el-button
                    v-else
                    class="button-new-tag ml-1 mb8"
                    size="small"
                    @click="showInput"
                  >
                    + 新增
                  </el-button>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-table :data="specFirstAttrTags">
                    <el-table-column :label="form.firstSpecName" width="150px">
                      <template #default="scope">
                        <el-tag
                          :key="scope.row.name"
                          class="mx-1"
                          closable
                          :disable-transitions="false"
                          @close="handleClose(scope.row)"
                        >
                          {{ scope.row.name }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="主图" width="150px">
                      <template #default="scope">
                        <span v-if="scope.row.mainImg">
                          <el-image
                            style="width: 40px; height: 40px"
                            v-for="img in scope.row.mainImg.split(',')"
                            :key="img"
                            size="small"
                            :src="img"
                          ></el-image>
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column label="轮播图">
                      <template #default="scope">
                        <span v-if="scope.row.carouselImg">
                          <el-image
                            style="width: 40px; height: 40px"
                            v-for="img in scope.row.carouselImg.split(',')"
                            :key="img"
                            size="small"
                            :src="img"
                          ></el-image>
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      align="center"
                      class-name="small-padding fixed-width"
                    >
                      <template #default="scope">
                        <el-button
                          type="text"
                          size="small"
                          icon="upload-filled"
                          @click="
                            () => {
                              let callback = () => {
                                scope.row.mainImg = getSubImg();
                              };
                              handleImgUploadClick(scope.row.mainImg,1,callback);
                            }
                          "
                          >主 图</el-button
                        >
                        <el-button
                          type="text"
                          size="small"
                          icon="upload-filled"
                          @click="
                            () => {
                              let callback = () => {
                                scope.row.carouselImg = getSubImg();
                              };
                              handleImgUploadClick(scope.row.carouselImg,9,callback);
                            }
                          "
                          >详情图</el-button
                        >
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </div>

            <!-- 规格二设置 -->
            <el-row v-if="form.specType > 1" class="mt-10 mb-4">
              <el-col :span="2">
                <span>{{form.secondSpecName}}</span>
              </el-col>
              <el-col :span="4">
                <el-input
                v-if="input2Visible"
                ref="Input2Ref"
                v-model="input2Value"
                class="w-10"
                size="small"
                @keyup.enter="handleInput2Confirm"
                @blur="handleInput2Confirm"
              />
              <el-button
                v-else
                class="button-new-tag ml-1 mb8"
                size="small"
                type="warning"
                plain
                @click="showInput2"
              >
                + 新增
              </el-button>
              </el-col>
              <el-col :span="12">
                <el-tag
                v-for="tag in specSecondAttrTags"
                :key="tag"
                class="mr-10"
                closable
                type="warning"
                :disable-transitions="false"
                @close="handleClose2(tag)"
              >
                {{ tag }}
              </el-tag>
              </el-col>
            </el-row>
            <!-- #begin sku列表 -->
            <div  v-if="form.specType > 0">
              <el-divider></el-divider>
              <el-form 
              v-for="(spec,index) in specList" 
              :key="index"
              ref="specForm"
              :model="spec" :rules="rules" :inline="true" label-width="0">
                <el-form-item prop="firstSpecValue">
                  <span>{{spec.firstSpecValue}}</span>
                </el-form-item>
                <el-form-item v-if="form.specType > 1" prop="secondSpecValue">
                  <span>{{spec.secondSpecValue}}</span>
                </el-form-item>
                <el-form-item prop="marketPrice">
                      <el-input
                      type="number"
                      v-model="spec.marketPrice"
                      placeholder="市场价"
                    ></el-input>
                    </el-form-item>
                <el-form-item prop="costPrice">
                      <el-input
                      type="number"
                      v-model="spec.costPrice"
                      placeholder="成本价"
                    ></el-input>
                    </el-form-item>
                    <el-form-item prop="salePrice">
                      <el-input
                      type="number"
                      v-model="spec.salePrice"
                      placeholder="售价"
                    ></el-input>
                    </el-form-item>
                    <el-form-item prop="stockNum">
                      <el-input
                        type="number"
                        v-model="spec.stockNum"
                        placeholder="库存"
                      ></el-input>
                    </el-form-item>
                    <el-form-item prop="status">
                    <el-switch
                      inline-prompt
                      v-model="spec.status"
                      :active-value="0"
                      :inactive-value="1"
                      active-text="开"
                      inactive-text="关"
                    ></el-switch>
                    </el-form-item>

              </el-form>
            </div>
            <!-- #end sku列表 -->
          </div>
        </el-card>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogCancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传图片对话框 -->
    <el-dialog
      v-model="uploadImgDialogVisible"
      title="上传图片"
      width="800px"
      append-to-body
    >
    <div>
      <ImageUpload
        :modelValue="uploadImgValue"
        :limit="uploadImgLimit"
        @update:modelValue="(val) => (uploadImgValue = val)"
      ></ImageUpload>
    </div>
    <div>
      <el-checkbox v-model="rememberImg">保留上传</el-checkbox>
    </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="() => (uploadImgDialogVisible = false)"
            >取 消</el-button
          >
          <el-button type="primary" @click="handleUploadImgConfirm"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import { ref, toRefs } from "vue";
import { ElMessage } from 'element-plus';
import {
  listGoods,
  getEditDto,
  delGoods,
  addGoods,
  updateGoods,
  exportXlsUrl,
  getTreeData,
} from "@/api/product/goods";
import {getBrandSelectList} from "@/api/product/brand"
import {getCategorySelectTree} from "@/api/product/category"

const { proxy } = getCurrentInstance();

const { sys_normal_disable } = proxy.useDictNum("sys_normal_disable");

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 商品表格数据
const goodsList = ref([]);
// 弹出层标题
const dialogTitle = ref("");
// 是否显示弹出层
const dialogVisible = ref(false);
// 备注时间范围
const daterangeCreateTime = ref([]);

const uploadImgDialogVisible = ref(false);
const uploadImgValue = ref("");
const uploadImgLimit = ref(9);
const rememberImg = ref(true)

// 类目选项
const categoryOptions = ref([]);
// 品牌选项
const brandOptions = ref([]);

const specTypeOptions = ref([
  {
    value: 0,
    label: "无规格",
  },
  {
    value: 1,
    label: "单规格",
  },
  {
    value: 2,
    label: "双规格",
  },
]);

const specFirstAttrTags = ref([]);
const specSecondAttrTags = ref([]);
// 商品规格
const specList = ref([]);

const defaultSpec = ref({
  id: null,
  marketPrice: null,
  costPrice: null,
  salePrice: null,
  stockNum: null,
});

// 规格一
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref();

// 规格二
const input2Value = ref("");
const input2Visible = ref(false);
const Input2Ref = ref();

// 查询参数
const reactiveData = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeName: null,
    goodsName: null,
    goodsCode: null,
    barCode: null,
    categoryName: null,
    brandName: null,
    status: null,
    createTime: null,
    params: {
      sort: "createTime",
      order: "descending",
    },
  },
  form: {
  },
  rules: {
    goodsName: [
      { required: true, message: "商品名称不能为空", trigger: "blur" }
    ],
    // goodsCode: [
    //   { required: true, message: "商品编码不能为空", trigger: "blur" }
    // ],
    // barCode: [
    //   { required: true, message: "产品条码不能为空", trigger: "blur" }
    // ],
    
    
    // goodsDetail: [
    //   { required: true, message: "商品详情不能为空", trigger: "blur" }
    // ],
    //  defaultSpesalePrice: [
    //   { required: true, message: "售价不能为空", trigger: "blur" }
    // ],
    // defaultSpecstockNum: [
    //   { required: true, message: "库存不能为空", trigger: "blur" }
    // ],
    salePrice: [
      { required: true, message: "售价不能为空", trigger: "blur" }
    ],
    stockNum: [
      { required: true, message: "库存不能为空", trigger: "blur" }
    ],
  },
});

const { queryParams, form, rules } = toRefs(reactiveData);

const tableSort = computed(() => {
  if (queryParams.value.params.sort) {
    return {
      prop: queryParams.value.params.sort,
      order: queryParams.value.params.order,
    };
  }
  return null;
});

/** 查询商品列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime.value && "" != daterangeCreateTime.value) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listGoods(queryParams.value).then((response) => {
    goodsList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

function loadTreeData(row,treeNode,resolve){
  console.log('loadTreeData');
  getTreeData(row.id).then(response=>{
    console.log('loadTreeData res',response);
    resolve(response.data)
  })
}
// 取消按钮
function handleDialogCancel() {
  dialogVisible.value = false;
  reset();
}

function handleSelectable(row,index){
  return row.hasChildren;
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    merchantId: null,
    storeId: null,
    storeName: null,
    goodsName: null,
    goodsCode: null,
    barCode: null,
    goodsTitle: null,
    keyword: null,
    categoryId: null,
    categoryName: null,
    categoryList: null,
    brandId: null,
    brandName: null,
    goodsDetail: null,
    freightTemplateId: null,
    unitName: null,
    sortNum: null,
    saleNum: null,
    status: null,
    hotState: null,
    bestState: null,
    newState: null,
    showTime: null,
    offlineTime: null,
    giveIntegral: null,
    fictiNum: null,
    browseNum: null,
    qrCodePath: null,
    specType: 0,
    firstSpecName: '颜色',
    secondSpecName: '尺码',
    remark: null,
  };
  defaultSpec.value ={
    id: null,
    marketPrice: null,
    costPrice: null,
    salePrice: null,
    stockNum: null,
  } 

  proxy.resetForm("formRef");

}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryFormRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 排序
function handleSortChange({ column, prop, order }) {
  queryParams.value.params.sort = prop ? prop : null;
  queryParams.value.params.order = order ? order : null;
  getList();
}

function initSelection(){
  if(!brandOptions.value || brandOptions.value.length==0){
    getBrandSelectList().then(res=>{
      brandOptions.value = res.data;
    })
  }
  if(!categoryOptions.value || categoryOptions.value.length==0){
    getCategorySelectTree().then(res=>{
      categoryOptions.value = res.data;
    })
    
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  initSelection();
  dialogVisible.value = true;
  dialogTitle.value = "添加商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getEditDto(id).then((response) => {
    console.log('handleUpdate',response);
    // form.value = response.data;
    dialogVisible.value = true;
    dialogTitle.value = "修改商品";
    form.value=response.data.goods;
    specList.value = response.data.specList;
    defaultSpec.value = response.data.defaultSpec;
    specFirstAttrTags.value = response.data.specFirstAttrTags;
    specSecondAttrTags.value = response.data.specSecondAttrTags;
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef2"]?.validate(()=>{});
  if(form.value.specType>0 && specList.value.length>0){
    // for (let i = 0; i < specList.length; i++) {
    //   proxy.$refs["specForm"+i]?.validate(()=>{});
    // }
    const specFormRef = proxy.$refs["specForm"];
    if(specFormRef && specFormRef.length>0){
      specFormRef.forEach(item => {
        item.validate(()=>{});
      });
    }
  }
  proxy.$refs["formRef"].validate((valid) => {
    if(!valid){
      return;
    }

    if(form.value.specType==0){
      if(defaultSpec.value.salePrice==='' || defaultSpec.value.stockNum===''){
        return;
      }
    }

    if(form.value.specType>0 && specList.value.length==0){
      ElMessage.error('请录入规格信息')
      return;
    }

    // 校验规格值
    if(form.value.specType>0){

      for (let index = 0; index < specList.value.length; index++) {
        const item = specList.value[index];
        if(item.salePrice==='' || item.stockNum===''){
          return;
        }
      }
    }

    if (valid) {
      let data = {};
      const { specType } = form.value;
      if(specType==0){
        data = {
          goods: form.value,
          defaultSpec:defaultSpec.value,
        }
      }
      if(specType>0){
         data = {
          goods: form.value,
          specList: specList.value,
          specFirstAttrTags:specFirstAttrTags.value,
        }
        if(specType>1){
          data.specSecondAttrTags = specSecondAttrTags.value;
        }
      }


      if (form.value.id != null) {
        updateGoods(data).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          getList();
        });
      } else {
        addGoods(data).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          dialogVisible.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const rowids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除商品编号为"' + rowids + '"的数据项？')
    .then(function () {
      return delGoods(rowids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    exportXlsUrl,
    {
      ...queryParams.value,
    },
    `goods_${new Date().getTime()}.xlsx`
  );
}



const handleClose = (tag) => {
  specFirstAttrTags.value.splice(specFirstAttrTags.value.indexOf(tag), 1);
  specList.value = specList.value.filter(item=>{
    return item.firstSpecValue!=tag.name;
  })
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value?.input?.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    specFirstAttrTags.value.push({ name: inputValue.value });
    initSpecData();
  }
  inputVisible.value = false;
  inputValue.value = "";
};

const handleClose2 = (tag) => {
  specSecondAttrTags.value.splice(specSecondAttrTags.value.indexOf(tag), 1);
  specList.value = specList.value.filter(item=>{
    return item.secondSpecName!=tag;
  })
};

const showInput2 = () => {
  input2Visible.value = true;
  nextTick(() => {
    Input2Ref.value?.input?.focus();
  });
};

const handleInput2Confirm = () => {
  if (input2Value.value) {
    specSecondAttrTags.value.push(input2Value.value);
    initSpecData();
  }
  input2Visible.value = false;
  input2Value.value = "";
};

const uploadConfirmCallback = ref(() => {});

const handleUploadImgConfirm = () => {
  uploadImgDialogVisible.value = false;
  uploadConfirmCallback.value();
};

const handleImgUploadClick = (imgs,limit,callback) => {
  if(!rememberImg.value){
    uploadImgValue.value = imgs;
  }
  uploadImgLimit.value = limit;
  uploadImgDialogVisible.value = true;
  uploadConfirmCallback.value = callback;
}

const getSubImg = () => {
  let imgs = uploadImgValue.value;
  let limit = uploadImgLimit.value;
  if (!imgs) {
    return "";
  }
  let imgsArr = imgs.split(",");
  let subArr = [];
  for (let i = 0; i < imgsArr.length; i++) {
    if (i < limit) {
      subArr.push(imgsArr[i]);
    }
  }
  console.log('getSubImg',subArr.join(","));
  return subArr.join(",");
};

// 规格类型改变 
function handleSpecTypeChange(){
  if(form.value.specType<2){
    specSecondAttrTags.value = []
  }
  if(form.value.specType<1){
    specFirstAttrTags.value = []
  }
  specList.value = []
  initSpecData()
}

// 构建sku列表
const initSpecData = () =>{
  if(form.value.specType>0){
    specFirstAttrTags.value.forEach(firstTag => {
      if(form.value.specType==2){
        specSecondAttrTags.value.forEach(secondTag =>{
          if(!constainsSpec(firstTag.name,secondTag)){
            specList.value.push({
              firstSpecValue: firstTag.name,
              secondSpecValue: secondTag,
              status: 0,
            })
          }
        })
      }else{
        if(!constainsSpec(firstTag.name,undefined)){
            specList.value.push({
              firstSpecValue: firstTag.name,
              status: 0,
            })
          }
      }
    });
  }
  
  
}

function constainsSpec(specAttr1, specAttr2){
   let specArr =  specList.value.filter(item=>{
      let flag = true;
      if(specAttr1){
        flag = flag && item.firstSpecValue==specAttr1;
      }
      if(specAttr2){
        flag = flag && item.secondSpecValue==specAttr2;
      }
      return flag;
    })
  
  return specArr.length>0;;
}

/**
 * json 测试数据
 */
function initJsonData() {
  categoryOptions.value = [
    {
      value: 11,
      label: "手机通讯",
      children: [
        {
          value: 12,
          label: "手机",
        },
      ],
    },
    {
      value: 21,
      label: "男装",
      children: [
        {
          value: 22,
          label: "T恤",
        },
      ],
    },
  ];

  brandOptions.value = [
    {
      value: 11,
      label: "华为",
    },
    {
      value: 21,
      label: "苹果",
    },
    {
      value: 31,
      label: "小米",
    },
  ];

  loading.value = false;
  // let jsonStr = "[]";
  // goodsList.value = JSON.parse(jsonStr);
  goodsList.value = [
    {
      id: 1,
      goodsName: "测试商品名称t1",
      goodsCode: "G001",
      children: [
        {
          id: 2,
          goodsName: "蓝色",
          specCode: "S002",
        },
        {
          id: 3,
          goodsName: "绿色",
          specCode: "S003",
        },
      ],
    },
    {
      id: 21,
      goodsName: "测试商品名称t2",
      goodsCode: "G0021",
      children: [
        {
          id: 22,
          goodsName: "蓝色",
          specCode: "S0022",
        },
        {
          id: 23,
          goodsName: "绿色",
          specCode: "S0023",
        },
      ],
    },
  ];
}
/** 初始化数据 **/
 getList();
// initJsonData();
</script>

<style scoped>
.mt-20{
  margin-top: 20px;
}
.mt-10{
  margin-top: 10px;
}
.mr-10{
  margin-right: 10px;
}
</style>